package com.example.wanglong.myapplication;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;

public class MainActivity extends AppCompatActivity {

    private EditText mNameView, mPassWordView, mPortView;

    private ListView mListView;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);

            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,
                    (List<? extends Map<String, ?>>) msg.obj, R.layout.item_receiveemail, new String[] {
                    "from", "title", "time", "read" }, new int[] {
                    R.id.item_receive_sendname,
                    R.id.item_receive_title,
                    R.id.item_receive_sendtime,
                    R.id.item_receive_read });
            mListView.setAdapter(adapter);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNameView = findViewById(R.id.name);
        mPassWordView = findViewById(R.id.password);
        mPortView = findViewById(R.id.port);
        mListView = findViewById(R.id.list);
        findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        getEmail(getText(mNameView), getText(mPassWordView), 995);
//                        getEmail("1197183452@qq.com", "9860171234bB", 995);
                        getImapEmail(getText(mNameView), getText(mPassWordView));
                    }
                }).start();
            }
        });


    }

    private String getText(EditText editText) {
        if (editText.getText() != null && !TextUtils.isEmpty(editText.getText().toString())) {
            return editText.getText().toString();
        }
        return "";
    }

    /**
     * 以pop3方式读取邮件，此方法不能读取邮件是否为已读，已经通过测试
     * */
    private void getEmail(String name, String password, int port) {
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            Properties props = System.getProperties();

            /*网易*/
//            props.put("mail.smtp.host", "smtp.163.com");
//            props.put("mail.smtp.auth", "true");
//            Session session = Session.getDefaultInstance(props, null);
//            URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
//                    "wlong8000@163.com", "wlong@zjl123");

            /*阿里*/
            props.put("mail.smtp.host", "smtp.163.com");
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, null);
            URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
                    "wlong8000@163.com", "wlong@zjl123");


            // 邮件协议为pop3，邮件服务器是pop3.163.com，端口为110，用户名/密码为abcw111222/123456w
            Store store = session.getStore(urln);
            store.connect();
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            Message message[] = folder.getMessages();
            if (message.length > 0) {
                Map<String, Object> map;
                System.out.println("Messages's length: " + message.length);
                ReciveOneMail pmm = null;
                for (int i = 0; i < message.length; i++) {
                    System.out.println("======================");
                    pmm = new ReciveOneMail((MimeMessage) message[i]);
                    System.out.println("Message " + i + " subject: "
                            + pmm.getSubject());
                    System.out.println("Message " + i + " sentdate: "
                            + pmm.getSentDate());
                    System.out.println("Message " + i + " replysign: "
                            + pmm.getReplySign());

                    boolean isRead = pmm.isNew();// 判断邮件是否为已读
                    System.out.println("Message " + i + " hasRead: " + isRead);
                    System.out.println("Message " + i + "  containAttachment: "
                            + pmm.isContainAttach((Part) message[i]));
                    System.out.println("Message " + i + " form: "
                            + pmm.getFrom());
                    System.out.println("Message " + i + " to: "
                            + pmm.getMailAddress("to"));
                    System.out.println("Message " + i + " cc: "
                            + pmm.getMailAddress("cc"));
                    System.out.println("Message " + i + " bcc: "
                            + pmm.getMailAddress("bcc"));
                    pmm.setDateFormat("yy年MM月dd日 HH:mm");
                    System.out.println("Message " + i + " sentdate: "
                            + pmm.getSentDate());
                    System.out.println("Message " + i + " Message-ID: "
                            + pmm.getMessageId());
                    // 获得邮件内容===============
                    pmm.getMailContent((Part) message[i]);
                    System.out.println("Message " + i + " bodycontent: \r\n"
                            + pmm.getBodyText());
                    String file_path = File.separator + "mnt" + File.separator
                            + "sdcard" + File.separator;
                    System.out.println(file_path);
                    pmm.setAttachPath(file_path);
                    pmm.saveAttachMent((Part) message[i]);

                    map = new HashMap<String, Object>();
                    map.put("from", pmm.getFrom());
                    map.put("title", pmm.getSubject());
                    map.put("time", pmm.getSentDate());
                    map.put("read", isRead);
                    list.add(map);
                }
                Log.i("TAG", "========LIST=======" + list.size());
                android.os.Message message1 = new android.os.Message();
                message1.obj = list;
                handler.sendMessage(message1);


            } else {
                Toast.makeText(MainActivity.this, "没有邮件", Toast.LENGTH_SHORT)
                        .show();
            }
        } catch (final Exception e) {
            Log.i("TAG", "========Exception=======" + e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT)
                            .show();
                }
            });

        }
    }

    /**
     * 以imap方式读取邮件，可以判定读取邮件是否为已读
     */
    private void getImapEmail(String userName, String pwd) {
        String user = "test@vizumtech.com";// 邮箱的用户名
        String password = "123456aA"; // 邮箱的密码
        if (!TextUtils.isEmpty(userName)) {
            user = userName;
        }

        if (!TextUtils.isEmpty(pwd)) {
            password = pwd;
        }

        Properties prop = System.getProperties();
        prop.put("mail.store.protocol", "imap");
        prop.put("mail.imap.host", "imap.mxhichina.com");

        Session session = Session.getInstance(prop);

        int total = 0;
        IMAPStore store;
        try {
            store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制，连接服务器

            store.connect(user, password);

            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
            folder.open(Folder.READ_WRITE);
            // 获取总邮件数
            total = folder.getMessageCount();
            System.out.println("---共有邮件：" + total + " 封---");
            // 得到收件箱文件夹信息，获取邮件列表
            List<Map<String, Object>> list = new ArrayList<>();
            System.out.println("未读邮件数：" + folder.getUnreadMessageCount());
            Message[] messages = folder.getMessages();
            if (messages.length > 0) {
                Map<String, Object> map;
                System.out.println("Messages's length: " + messages.length);
                ReciveOneMail pmm = null;
                for (int i = 0; i < messages.length; i++) {
                    System.out.println("======================" + messages[i]);
                    pmm = new ReciveOneMail((MimeMessage) messages[i]);
                    System.out.println("Message " + i + " subject: "
                            + pmm.getSubject());
                    try {
                        System.out.println("Message " + i + " sentdate: "
                                + pmm.getSentDate());
                        System.out.println("Message " + i + " replysign: "
                                + pmm.getReplySign());

                        boolean isRead;// 用来判断该邮件是否为已读
                        String read;
                        Flags flags = messages[i].getFlags();
                        if (flags.contains(Flags.Flag.SEEN)) {
                            System.out.println("这是一封已读邮件");
                            isRead = true;
                            read = "已读";
                        } else {
                            System.out.println("未读邮件");
                            isRead = false;
                            read = "未读";
                        }
                        System.out.println("Message " + i + " hasRead: "
                                + isRead);
                        System.out.println("Message " + i
                                + "  containAttachment: "
                                + pmm.isContainAttach((Part) messages[i]));
                        System.out.println("Message " + i + " form: "
                                + pmm.getFrom());
                        System.out.println("Message " + i + " to: "
                                + pmm.getMailAddress("to"));
                        System.out.println("Message " + i + " cc: "
                                + pmm.getMailAddress("cc"));
                        System.out.println("Message " + i + " bcc: "
                                + pmm.getMailAddress("bcc"));
                        pmm.setDateFormat("yy年MM月dd日 HH:mm");
                        System.out.println("Message " + i + " sentdate: "
                                + pmm.getSentDate());
                        System.out.println("Message " + i + " Message-ID: "
                                + pmm.getMessageId());
                        // 获得邮件内容===============
                        pmm.getMailContent((Part) messages[i]);
                        System.out.println("Message " + i
                                + " bodycontent: \r\n" + pmm.getBodyText());
                        String file_path = File.separator + "mnt"
                                + File.separator + "sdcard" + File.separator;
                        System.out.println(file_path);
                        pmm.setAttachPath(file_path);
                        pmm.saveAttachMent((Part) messages[i]);

                        map = new HashMap<String, Object>();
                        map.put("from", pmm.getFrom());
                        map.put("title", pmm.getSubject());
                        map.put("time", pmm.getSentDate());
                        map.put("read", read);
                        list.add(map);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                Log.i("TAG", "========LIST=======" + list.size());
                android.os.Message message1 = new android.os.Message();
                message1.obj = list;
                handler.sendMessage(message1);
//                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,
//                        list, R.layout.item_receiveemail, new String[]{
//                        "from", "title", "time", "read"}, new int[]{
//                        R.id.item_receive_sendname,
//                        R.id.item_receive_title,
//                        R.id.item_receive_sendtime,
//                        R.id.item_receive_read});
//                lv.setAdapter(adapter);
            }
        } catch (javax.mail.NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
